//
//  QRCodeViewController.swift
//  WeiBoSwift
//
//  Created by rong on 15/6/30.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

    ///冲击波的顶部约束
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    
    ///扫描容器的高度约束
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
   
    ///扫描容器的宽度约束
    @IBOutlet weak var withConstraint: NSLayoutConstraint!
    
    
    @IBOutlet weak var tabBar: UITabBar!
    //关闭当前控制器
    @IBAction func close(sender: AnyObject) {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        //下面的tabbar默认选中第一项
        tabBar.selectedItem = tabBar.items![0]
        
        //设置二维码的扫描环境
        setupSession()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
       
        // 开始扫描动画
        startAnimation()
        
        // 开始扫描   !!!必须 启动会话之后，才能开始扫描
        startScan()
    }
    
    //tabbar的代理是self, 在storyboard上设置的
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem)
    {
        //二维码和条形码之间切换，高度改变
        heightConstraint.constant = withConstraint.constant * (item.tag == 1 ? 0.5 : 1)
        
        startAnimation()
    }
    
    //扫描动画
    private func startAnimation(){
        
        topConstraint.constant = -heightConstraint.constant
        view.layoutIfNeeded()
        
        UIView.animateWithDuration(2.0) { () -> Void in
            
            //次数
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.topConstraint.constant = self.heightConstraint.constant
            self.view.layoutIfNeeded()
            
        }
    }
    
    //开始二维码扫描
    private func startScan(){
        
        session.startRunning()
    }
    
    //设置会话
    private func setupSession()
    {
        // 1.判断能否添加设备
        if !session.canAddInput(inputDevice) {
            print("无法添加输入设备")
            return
        }
        
        // 2.判断能够添加输出数据
        if !session.canAddOutput(outputData) {
            print("无法添加输出数据")
            return
        }
        
        // 3.添加设备
        session.addInput(inputDevice)
        print("前 \(outputData.availableMetadataObjectTypes)")
        // 添加输出数据
        session.addOutput(outputData)
        // !!!只有添加到  session 后，输出数据的数据类型才可以用
        print("后 \(outputData.availableMetadataObjectTypes)")
        
        //4.设置扫描数据类型
        outputData.metadataObjectTypes = outputData.availableMetadataObjectTypes
        
        //5.设置数据的代理
        outputData.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        
    }
    
    //扫描数据代理
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        
    }
    
    //设置图层
    private func setupLayers()
    {
        //1.设置绘图图层
        drawLayer.frame = view.bounds
        view.layer.insertSublayer(drawLayer, atIndex: 0)
        
        //2.预览图层，设定图层大小
    }
    
    
  // ===>  工具懒加载  <===
    
    //1.拍摄会话, 扫描的桥梁
    lazy var session : AVCaptureSession = AVCaptureSession()
    
    //2.摄像头输入设备
    lazy var inputDevice : AVCaptureDeviceInput? = {
    
        //取摄像头设备
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        
        do{
            return try AVCaptureDeviceInput(device : device)
        
        } catch {
            print("获取摄像头输入设备错误 ==》 \(error)")
            return nil
        }
    }()
    
    //3.输出数据
    lazy var outputData : AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    //4.绘制图层的懒加载
    lazy var drawLayer : CALayer = CALayer()
    
}
